from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy, reverse
from django.contrib import messages
from django.db.models import Q
from django.http import JsonResponse, HttpResponse

from .models import CursorRule, Tag
from .forms import CursorRuleForm
from core.models import SiteInfo, ActionCount, PageVisitCount, Advertisement

class RuleListView(ListView):
    """规则列表视图"""
    model = CursorRule
    template_name = 'rules/rule_list.html'
    context_object_name = 'rules'
    paginate_by = 12
    
    def get_queryset(self):
        queryset = CursorRule.objects.filter(status='approved').select_related('author').prefetch_related('tags')
        
        # 搜索
        search_query = self.request.GET.get('q')
        if search_query:
            queryset = queryset.filter(
                Q(title__icontains=search_query) | 
                Q(content__icontains=search_query) |
                Q(tags__name__icontains=search_query)
            ).distinct()
        
        # 标签筛选
        tags = self.request.GET.getlist('tags')
        if tags:
            queryset = queryset.filter(tags__id__in=tags).distinct()
        
        return queryset
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['language_tags'] = Tag.objects.filter(category='language')
        context['scenario_tags'] = Tag.objects.filter(category='scenario')
        context['site_info'] = SiteInfo.get_site_info()
        context['query'] = self.request.GET.get('q', '')
        
        # 获取选中的标签ID（作为字符串列表保存）
        context['selected_tags'] = self.request.GET.getlist('tags')
        
        # 获取活跃广告
        ads = Advertisement.objects.filter(is_active=True).order_by('display_order')
        
        # 确保广告图片URL是有效的
        for ad in ads:
            if ad.image and not ad.image.name.startswith('ads/'):
                # 确保路径中包含ads/前缀
                if '/' in ad.image.name:
                    ad.image.name = f"ads/{ad.image.name.split('/')[-1]}"
                else:
                    ad.image.name = f"ads/{ad.image.name}"
                    
        context['ads'] = ads
        
        # 为规则添加访问量
        rules_with_visits = list(context['rules'])
        rule_ids = [rule.id for rule in rules_with_visits]
        rule_visits = dict(
            PageVisitCount.objects.filter(
                content_type='rule', 
                object_id__in=rule_ids
            ).values_list('object_id', 'visit_count')
        )
        for rule in rules_with_visits:
            rule.visit_count = rule_visits.get(rule.id, 0)
            
        return context

class RuleDetailView(DetailView):
    """规则详情视图"""
    model = CursorRule
    template_name = 'rules/rule_detail.html'
    context_object_name = 'rule'
    
    def get_queryset(self):
        return CursorRule.objects.filter(status='approved').select_related('author').prefetch_related('tags')
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        rule = self.get_object()
        
        # 查找相关规则
        related_rules = CursorRule.objects.filter(
            status='approved'
        ).filter(
            tags__in=rule.tags.all()
        ).exclude(
            id=rule.id
        ).distinct()[:5]
        
        context['related_rules'] = related_rules
        context['site_info'] = SiteInfo.get_site_info()
        return context

class RuleSubmitView(LoginRequiredMixin, CreateView):
    """规则提交视图"""
    model = CursorRule
    form_class = CursorRuleForm
    template_name = 'rules/rule_submit.html'
    success_url = reverse_lazy('rules:submit_success')
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['site_info'] = SiteInfo.get_site_info()
        context['language_tags'] = Tag.objects.filter(category='language')
        context['scenario_tags'] = Tag.objects.filter(category='scenario')
        return context
    
    def form_valid(self, form):
        form.instance.author = self.request.user
        form.instance.status = 'pending'
        messages.success(self.request, '规则提交成功，等待管理员审核。')
        return super().form_valid(form)

def submit_success_view(request):
    """规则提交成功视图"""
    return render(request, 'rules/submit_success.html', {
        'site_info': SiteInfo.get_site_info()
    })

def copy_rule_content(request, pk):
    """复制规则内容，同时记录复制操作统计"""
    rule = get_object_or_404(CursorRule, pk=pk, status='approved')
    
    # 记录复制操作
    ActionCount.increment_count('copy_rule', rule.id)
    
    return JsonResponse({
        'success': True,
        'content': rule.content,
    })

def record_md_view(request, pk):
    """记录查看MD格式的操作"""
    rule = get_object_or_404(CursorRule, pk=pk, status='approved')
    
    # 记录MD格式查看操作
    ActionCount.increment_count('view_rule_md', rule.id)
    
    return JsonResponse({'success': True})

def download_rule_md(request, pk):
    """下载规则内容为Markdown文件"""
    rule = get_object_or_404(CursorRule, pk=pk, status='approved')
    
    # 记录下载操作
    ActionCount.increment_count('download_rule_md', rule.id)
    
    # 创建文件名(使用规则标题并替换不合法字符)
    filename = rule.title.replace(' ', '_').replace('/', '_').replace('\\', '_')
    filename = ''.join(c for c in filename if c.isalnum() or c in '_-.')
    if not filename:
        filename = f"rule_{rule.id}"
    
    # 创建响应，确保使用UTF-8编码
    response = HttpResponse(rule.content.encode('utf-8'), content_type='text/markdown; charset=utf-8')
    response['Content-Disposition'] = f'attachment; filename="{filename}.md"'
    return response

def get_rule_url(request, pk):
    """获取规则页面的URL"""
    rule = get_object_or_404(CursorRule, pk=pk, status='approved')
    
    # 记录获取URL操作
    ActionCount.increment_count('copy_rule_url', rule.id)
    
    # 构建完整URL
    rule_url = request.build_absolute_uri(reverse('rules:detail', args=[rule.id]))
    
    return JsonResponse({
        'success': True,
        'url': rule_url,
    })
